using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace ScreenResolutionMaintenance
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        public static Rectangle RenderArea { get { return new Rectangle(0, 0, 800, 480); } }
        public Rectangle RenderRatio 
        { 
            get 
            {
                int top = (GraphicsDevice.Viewport.TitleSafeArea.Height - RenderArea.Height) / 2;
                int lft = (GraphicsDevice.Viewport.TitleSafeArea.Width - RenderArea.Width) / 2;
                return new Rectangle(lft, top, (int)(GraphicsDevice.Viewport.TitleSafeArea.Width * Ratio.X), (int)(GraphicsDevice.Viewport.TitleSafeArea.Height * Ratio.Y)); 
            }
        }
        public static Vector2 RenderAreaCenter { get { return new Vector2(RenderArea.Width / 2, RenderArea.Height / 2); } }

        public Vector2 Ratio
        {
            get
            {
                Vector2 tsr = new Vector2((float)RenderArea.Width / (float)GraphicsDevice.Viewport.TitleSafeArea.Width, (float)RenderArea.Height / (float)GraphicsDevice.Viewport.TitleSafeArea.Height);
                return tsr;
            }
        }

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public RenderTarget2D finalRT;

        public Texture2D white;

        public SoundManager sndMgr;

        bool PlayMusic1;

        KeyboardState thisKB;
        KeyboardState lastKB;

        SpriteFont font;

        bool IsKeyPressed(Keys key)
        {
            return thisKB.IsKeyUp(key) && lastKB.IsKeyDown(key);
        }
        bool IsKeyDown(Keys key)
        {
            return thisKB.IsKeyDown(key) && lastKB.IsKeyDown(key);
        }

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

            Window.AllowUserResizing = true;
            IsMouseVisible = true;

            graphics.PreferredBackBufferWidth = 960;
            graphics.PreferredBackBufferHeight = 600;

            sndMgr = new SoundManager(this);

            PlayMusic1 = true;

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            finalRT = new RenderTarget2D(GraphicsDevice, RenderArea.Width, RenderArea.Height);

            // Load your music and sfx here
            sndMgr.LoadMusic("music1", "Audio/music/music1", .25f);
            sndMgr.LoadMusic("music2", "Audio/music/music2", .25f);

            sndMgr.LoadSFX("sfx1", "audio/sfx/sfx1");
            sndMgr.LoadSFX("sfx2", "audio/sfx/sfx2");
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            white = new Texture2D(GraphicsDevice, 1, 1);
            white.SetData<Color>(new Color[] { new Color(1f,1f,1f,.25f) });

            font = Content.Load<SpriteFont>("fonts/font");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            thisKB = Keyboard.GetState();

            // Allows the game to exit
            if (IsKeyPressed(Keys.Escape))
                this.Exit();

            if (PlayMusic1 && !sndMgr.IsMusicPlaying("music1"))
                sndMgr.PlayMusic("music1");
            // When stuff happens, play sound/music
            if (IsKeyPressed(Keys.F1))
            {
                PlayMusic1 = false;
                sndMgr.StopMusic("music1");
                sndMgr.PlayMusic("music2");
            }

            if (IsKeyPressed(Keys.F2))
            {
                PlayMusic1 = true;
                sndMgr.StopMusic("music2");
                sndMgr.PlayMusic("music1");
            }

            if (IsKeyPressed(Keys.F3))
            {
                PlayMusic1 = true;
                sndMgr.PlayMusic("music2");
                sndMgr.PlayMusic("music1");
            }

            if (IsKeyPressed(Keys.F4))
                sndMgr.PlayInstantSFX("sfx1");

            if (IsKeyPressed(Keys.F5))
                sndMgr.PlayInstantSFX("sfx2");

            if (IsKeyPressed(Keys.F6))
                sndMgr.FadeALLMusicOut();

            if (IsKeyPressed(Keys.F7))
                sndMgr.FadeALLMusicIn();

            if (IsKeyDown(Keys.Up))
                sndMgr.AlterALLPlayingMusicVolume(.01f);

            if (IsKeyDown(Keys.Down))
                sndMgr.AlterALLPlayingMusicVolume(-.01f);

            if (IsKeyDown(Keys.Space))
            {
                PlayMusic1 = false;
                sndMgr.StopALL();
            }

            base.Update(gameTime);

            lastKB = thisKB;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(finalRT);
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // Example Draw, put a red square in the center of the render area.
            spriteBatch.Begin();
            spriteBatch.Draw(white, new Rectangle((int)RenderAreaCenter.X - 16, (int)RenderAreaCenter.Y - 16, 32, 32), Color.Blue);

            spriteBatch.DrawString(font, "Esc - Exit", Vector2.Zero + new Vector2(0, font.LineSpacing * 0), Color.Gold);
            spriteBatch.DrawString(font, "F1  - Switch Music", Vector2.Zero + new Vector2(0, font.LineSpacing * 1), Color.Gold);
            spriteBatch.DrawString(font, "F2  - Switch Music Back", Vector2.Zero + new Vector2(0, font.LineSpacing * 2), Color.Gold);
            spriteBatch.DrawString(font, "F3  - Play Both", Vector2.Zero + new Vector2(0, font.LineSpacing * 3), Color.Gold);
            spriteBatch.DrawString(font, "Arrow Keys Up/Down  - Current Playing music volume", Vector2.Zero + new Vector2(0, font.LineSpacing * 4), Color.Gold);
            spriteBatch.DrawString(font, "F4  - Play Instant SFX1", Vector2.Zero + new Vector2(0, font.LineSpacing * 5), Color.Gold);
            spriteBatch.DrawString(font, "F5  - Play Instant SFX2", Vector2.Zero + new Vector2(0, font.LineSpacing * 6), Color.Gold);
            spriteBatch.DrawString(font, "F6  - Fade Music Out", Vector2.Zero + new Vector2(0, font.LineSpacing * 7), Color.Gold);
            spriteBatch.DrawString(font, "F7  - Fade Music In", Vector2.Zero + new Vector2(0, font.LineSpacing * 8), Color.Gold);
            spriteBatch.DrawString(font, "Space  - Stop all", Vector2.Zero + new Vector2(0, font.LineSpacing * 9), Color.Gold);
            
            spriteBatch.End();

            base.Draw(gameTime);

            GraphicsDevice.SetRenderTarget(null); 
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
            spriteBatch.Draw(finalRT, RenderRatio, Color.White);
            spriteBatch.End();
        }
    }
}
